package com.uroad.liaoningpos.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.ums.AppHelper;
import com.uroad.liaoningpos.R;
import com.uroad.liaoningpos.common.BaseActivity;
import com.uroad.liaoningpos.common.CurrApplication;
import com.uroad.liaoningpos.common.SPContants;
import com.uroad.liaoningpos.dialog.UpdateVersionDialog;
import com.uroad.liaoningpos.model.MessageEvent;
import com.uroad.liaoningpos.model.TransData;
import com.uroad.liaoningpos.model.VersionMDL;
import com.uroad.liaoningpos.service.DeviceService;
import com.uroad.liaoningpos.service.UploadService;
import com.uroad.liaoningpos.util.DownLoadUtils;
import com.uroad.liaoningpos.util.SPUtils;
import com.uroad.liaoningpos.util.SystemUtil;
import com.uroad.liaoningpos.webService.PosWS;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.widget.dialog.DialogHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @创建者 wlw
 * @创建时间 2019/4/2 15:35
 * @描述 首页 (中行版)
 */
public class MainActivity extends BaseActivity {
    private static String TAG = "MainActivity";
    @BindView(R.id.ivHeadPic)
    ImageView   ivHeadPic;
    @BindView(R.id.tvUserName)
    TextView    tvUserName;
    @BindView(R.id.tvNumber)
    TextView    tvNumber;
    @BindView(R.id.ibUserInfo)
    ImageButton ibUserInfo;
    @BindView(R.id.tvCheckoutCounter)
    TextView    tvCheckoutCounter;
    @BindView(R.id.tvPayDetails)
    TextView    tvPayDetails;
    @BindView(R.id.tvOrderCancel)
    TextView    tvOrderCancel;
    @BindView(R.id.tvOrderQuery)
    TextView    tvOrderQuery;
    @BindView(R.id.tvSettleAccounts)
    TextView    tvSettleAccounts;

    private UpdateVersionDialog updateDialog;
    private SingleDownloadTask downloadTask;
    private String appDownloadUrl = "";
    private boolean isMustUpdate = false;
    private long progress = 0;
    private boolean isConnectDevice;
    private DeviceService deviceService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayoutWithoutTitle(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        setData();
//        setListener();
        getVersionInfo();
        deviceService = new DeviceService(this);
        deviceService.connect();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initUploadService();
    }

    private void initUploadService() {
        Intent intent = new Intent(this, com.uroad.liaoningpos.service.UploadService.class);
        startService(intent);
    }

    private void setData() {
//        updateDialog = new UpdateVersionDialog(this);
        String username = (String) SPUtils.get(this, SPContants.SP_USERNAME, "");
        String departmentid = (String) SPUtils.get(this, SPContants.SP_MERCHANTSHOPID, "");
        tvUserName.setText(username);
        tvNumber.setText("商户编号：" + departmentid);
    }

    private void getVersionInfo() {
        String deviceuuid = (String) SPUtils.get(this, SPContants.SP_DEVICEUUID, "");
        //获取版本信息
        doRequest(PosWS.appVersion, PosWS.appVersionParams(deviceuuid), PosWS.appVersion);
    }

    public void setConnectState(final boolean isConnect){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                isConnectDevice = isConnect;
                if(isConnect){

                }else{

                }
            }
        });
    }

    @OnClick({R.id.ibUserInfo,R.id.tvCheckoutCounter,R.id.tvPayDetails,R.id.tvOrderCancel,R.id.tvOrderQuery,R.id.tvSettleAccounts})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ibUserInfo:
                openActivity(UserInfoActivity.class);
                break;
            case R.id.tvCheckoutCounter://收银台
                if(isConnectDevice)
                    openActivity(CheckoutCounterActivity.class);
                else
                    showShortToast("正在连接服务。。。");
                break;
            case R.id.tvPayDetails://余额查询
                //                openActivity(BalanceQueryActivity.class);
                balanceQuery();
                break;
            case R.id.tvOrderCancel://订单撤销
                openActivity(SelectCancelTypeActivity.class);
                break;
            case R.id.tvOrderQuery://订单查询
                openActivity(OrderQueryActivity.class);
                break;
            case R.id.tvSettleAccounts://结算换班
                openActivity(SettleAccountsActivity.class);
                break;
        }
    }

    /**余额查询*/
    private void balanceQuery() {
        org.json.JSONObject json = null;
        try {
            json = new org.json.JSONObject("{}");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        AppHelper.callTrans(this, "公共资源", "余额查询", json);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventMessage(MessageEvent event){
        if ("close".equalsIgnoreCase(event.getMessage())) {
            SPUtils.remove(this, SPContants.SP_TICKETID);
            SPUtils.remove(this, SPContants.SP_USERUUID);
            SPUtils.remove(this, SPContants.SP_MERCHANTSHOPID);
            SPUtils.remove(this, SPContants.SP_POSMERCHANTNO);
            SPUtils.remove(this, SPContants.SP_SHOPNAME);
            SPUtils.remove(this, SPContants.SP_USERNAME);
            SPUtils.remove(this, SPContants.SP_BEONDUTY);
            finish();
        }
    }

    public String getVersion() {
        try {
            String version =  (String) SPUtils.get(this, SPContants.SP_APPVERSION, "");
            if (TextUtils.isEmpty(version)) {
                version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            }
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            showShortToast("获取版本号异常");
            return null;
        }
    }

    @Override
    public void OnHttpTaskComplete(String result, String id) {
        super.OnHttpTaskComplete(result, id);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (FastJsonUtils.getJsonStatu00(jsonObject)) {
            if (PosWS.appVersion.equalsIgnoreCase(id)) {
//                final VersionMDL mdl = FastJsonUtils.parseDataObjectJSON(jsonObject, VersionMDL.class);
//                if (mdl != null) {
//                    final String version = getVersion();
//                    if (SystemUtil.isNeedUpdate(version, mdl.getVersion()) || SystemUtil.isNeedUpdate(version, mdl.getMinversion())) {
//                        String content = mdl.getUpdatelog();
//                        updateDialog.setTitle("发现新版本,是否更新？");
//                        updateDialog.setContent(content);
//                        appDownloadUrl = mdl.getDownloadurl();
//                        if (SystemUtil.isNeedUpdate(version, mdl.getMinversion())) {
//                            //强制升级
//                            isMustUpdate = true;
//                        }
//                        updateDialog.show();
//                    }
//                }
            }
        }
    }

    private void setListener() {
        updateDialog.setOkClickListener(new UpdateVersionDialog.OkClickListener() {
            @Override
            public void okClick() {
                updateDialog.hideCancelbtn(true);
                updateDialog.setOkBtnEnable(false);
                updateDialog.setBtnText("正在更新中", "");
                startDownload();
            }

            @Override
            public void cancelClick() {
                updateDialog.dismiss();
                if (isMustUpdate) {
                    finish();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        deviceService.disconnect();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        DialogHelper.endLoading();
        if (AppHelper.TRANS_REQUEST_CODE == requestCode) {
            LogUtil.d(TAG, "resultCode" + resultCode);
            if (Activity.RESULT_OK == resultCode) {
                if (null != data) {
                    Log.i(TAG, "requestCode----->" + requestCode + "\nresultCode----->" + resultCode + "\ndata Extra(result)" + data.getStringExtra("result"));
                    getPayResult(data);
                } else {
                    LogUtil.i(TAG, "Intent is null" + "\n");
                }
            } else {
                LogUtil.i(TAG, "resultCode is not RESULT_OK" + "\n");
            }
        }
    }

    private void getPayResult(Intent data) {
        StringBuilder result = new StringBuilder();
        Map<String, String> map = AppHelper.filterTransResult(data);
        result.append("{\"" + AppHelper.TRANS_APP_NAME + "\":\"" + map.get(AppHelper.TRANS_APP_NAME) + "\",");
        result.append("\"" + AppHelper.TRANS_BIZ_ID + "\":\"" + map.get(AppHelper.TRANS_BIZ_ID) + "\",");
        result.append("\"" + AppHelper.RESULT_CODE + "\":\"" + map.get(AppHelper.RESULT_CODE) + "\",");
        result.append("\"" + AppHelper.RESULT_MSG + "\":\"" + map.get(AppHelper.RESULT_MSG) + "\",");
        result.append("\"" + AppHelper.TRANS_DATA + "\":" + map.get(AppHelper.TRANS_DATA) + "}");
        LogUtil.i(TAG,"余额查询结果："+result.toString());
    }

    private void startDownload() {
        //TODO 调用系统下载 只能在wifi或移动网络状态下下载 插网线状态下无法下载
        //				Intent intent = new Intent(LoadActivity.this, UpdateService.class);
        //				intent.putExtra("url",appDownloadUrl);
        //				startService(intent);
        //				ToastUtil.show(LoadActivity.this,"开始下载最新安装包...");

        // 下载 由于插网线情况下无法调用系统下载 有以下几种方法
        //方法一、使用系统浏览器下载 但下载完成后需手动点击打开安装程序
        //				DownLoadUtils.downLoad(mContext, appDownloadUrl);
        //				DownLoadUtils.downLoadForView(mContext, appDownloadUrl);
        //				MyApplication.mServiceManager.downLoad(appDownloadUrl);

        //方法二、使用http方式异步下载
        if (downloadTask != null && downloadTask.getStatus()== AsyncTask.Status.RUNNING) {
            return;
        }
        //        tv_ok.setText("正在下载");
        //        tv_ok.setEnabled(false);
        downloadTask = new SingleDownloadTask();
        downloadTask.execute();
    }

    @SuppressLint("StaticFieldLeak")
    public class SingleDownloadTask extends AsyncTask<String, Integer, String> {
        private File file;

        @Override
        protected String doInBackground(String... strings) {
            try {
                String fileName = appDownloadUrl.substring(appDownloadUrl.lastIndexOf("/")+1);
                String filePath = Environment.getExternalStorageDirectory()+ File.separator + fileName;
                //新建要写入的文件
                file = new File(filePath);
                //如果文件不存在，则新建文件
                if (!file.exists()) {
                    file.createNewFile();
                }else{
                    file.delete();
                    file.createNewFile();
                }
                //获取url路径
                URL url = new URL(appDownloadUrl);
                //获取url连接
                URLConnection connection = url.openConnection();
                //获取文件的总长度
                int length = connection.getContentLength();
                //				//显示文件大小
                //				Message msg = new Message();
                //				msg.what = length;
                //				handler.sendMessage(msg);
                //获取输入流
                InputStream is = connection.getInputStream();

                //获取输出流
                FileOutputStream os = new FileOutputStream(file);
                //通过字节读取，每次读取1024B
                byte[] array = new byte[1024];
                int sum = 0;
                int index = is.read(array);
                while (index != -1) {
                    //写出array，长度0-index
                    os.write(array, 0, index);
                    sum+=index;
                    //更新进度
                    publishProgress(sum, length);
                    index = is.read(array);
                }
                os.flush();
                os.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
                file.delete();
                return "";
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //更新下载进度
            progress = (long) values[0] * 100 / (long) values[1];
            updateDialog.setContent("下载进度：" + progress + "%");
            //            tv_content.setText(progress+"%");
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(!isFinishing()) {
                updateDialog.setOkBtnEnable(true);
                updateDialog.hideCancelbtn(false);
                updateDialog.setBtnText("下载完成", "");
                updateDialog.dismiss();
                //下载完成 运行下载文件
                //            tv_ok.setEnabled(true);
                if (file != null && file.length() > 0) {
                    String path = file.getAbsolutePath();
                    if (!TextUtils.isEmpty(path)) { //文件不为空，且下载完成
//                        String commandToRun = "adb ";
//                        try {
//                            Runtime.getRuntime().exec(commandToRun);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
                        Intent intent = DownLoadUtils.openFile(path);
                        startActivity(intent);

                        //                        int result = UpdateUtil.excuteSuCMD(path);
                        //                        if (result == 0) {
                        //                            LogUtil.d(TAG, "更新成功");
                        //                        } else {
                        //                            LogUtil.d(TAG, "更新失败");
                        //                        }
                    }
                } else {
                    LogUtil.d(TAG, "下载失败");
                    //                showShortToast("下载失败，稍后将重试");
                }
            }
        }
    }

}
